<?php
declare (strict_types=1);

namespace app\common\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Db;

class Recovery extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('recovery')
            ->setDescription('客户回收');
    }

    protected function execute(Input $input, Output $output)
    {
        $system = cache('System');
        if (!empty($system['more']['kfrecycleday'])) {
            // 说明启用了客服回收
            //to_kh_time
            //$kfrecycledaytime=date('Y-m-d H:i:s',strtotime("-{$system['more']['kfrecycleday']} day"));
            $kfrecycledaytime = strtotime("-{$system['more']['kfrecycleday']} day");
            //Db::table('crm_customer')->where("`status`=1  and `issuccess` <> 1 and `to_kh_time` < '{$kfrecycledaytime}' and `last_up_time` < '{$kfrecycledaytime}' ")->update(['status'=>2,'to_gh_time'=>date("Y-m-d H:i:s",time())]);
            //不包含已经成交的
            //Db::table('crm_customer')->where("`status`=1 and `to_kh_time` < '{$kfrecycledaytime}' and `last_up_time` < '{$kfrecycledaytime}'")->update(['status'=>2,'to_gh_time'=>time()]);
            //Db::table('crm_customer')->where("`status`=1 and `to_kh_time` < '{$kfrecycledaytime}' and `last_up_time` < '{$kfrecycledaytime}'")->update(['status'=>2,'to_gh_time'=>time()]);

            $list = Db::table('crm_customer')->where("`status`=1  and `issuccess` <> 1 and `to_kh_time` < '{$kfrecycledaytime}' and `last_up_time` < '{$kfrecycledaytime}'")->select();
            
            $time = time();
            if (!empty($list)) {
                //回收到公海
                $list_array = $list->toArray();
                foreach ($list_array as $customer) {
                    $tmp['pr_user_bef'] = $customer['pr_user'];
                    if (empty($tmp['pr_user_bef'])) {
                        $tmp['pr_user_bef'] = '';
                    }
                    $tmp['pr_user'] = '';
                    $tmp['status'] = 2;
                    $tmp['to_gh_time'] = $time;
                    Db::table('crm_customer')->where("`id` = " . $customer['id'])->update($tmp);

                }
                //进行邮件提醒
                $this->sendUsersByCustomers($list_array,1);
            }

            //至少回收前两天(1+1)，每天提醒一次
            $frontdaytime = strtotime("+" . ($system['more']['kfrecycleday'] + 1) . " day");
            $list_2 = Db::table('crm_customer')->where("`status`=1 and `issuccess` <> 1  and `to_kh_time` < '{$frontdaytime}' and `last_up_time` < '{$frontdaytime}'")->select();
            //$list_2 = Db::table('crm_customer')->where("`status`=1 ")->select();
            if (!empty($list_2)) {
                //即将回收到公海，进行邮件提醒
                $this->sendUsersByCustomers($list_2->toArray(),2);
            }
        }
        // 指令输出
        $output->writeln('客户回收成功');
    }


    /**
     * @param $list_2_array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function sendUsersByCustomers($list_2_array,$type = 1)
    {
        //查询对应销售人员
        $prs_users_name = array_unique(array_column($list_2_array, 'pr_user'));
        if (!empty($prs_users_name)) {
            foreach ($prs_users_name as $user_name) {
                if ($user_name) {
                    $temp_user = Db::table('admin')->where(['username' => $user_name])->find();
                    if (!empty($temp_user['email'])) {
                        $this->sendEmail($type, $temp_user['email']);
                    }
                }
            }
        }
    }

    /**
     * 发送邮件
     * @param int $type
     * @param string $email
     * @param string $content
     * @return false
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function sendEmail($type = 1, $email = '')
    {
        if (!$email) {
            return false;
        }
        //检查是否邮箱格式
        if (!is_email($email)) {
            return false;
        }
        //进行回收
        if ($type == 1) {
            $subject = "客户资源已被回收提醒";
            $content = "有客户资源已被回收到公海,请至CRM后台中进行跟进处理";
        } else {
            //即将回收
            $subject = "客户资源即将回收提醒";
            $content = "有客户资源即将回收到公海,请至CRM后台中进行跟进处理";
        }
        $res = send_email($email, $subject, $content);
        return $res;
    }
}
